<template>
  <div>
    <basic-container>
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="可参与" name="bidOrder">
          <avue-crud
            :option="bidOption"
            :data="bidData"
            :table-loading="tableLoading"
            :page="page"
            ref="crud"
            @size-change="sizeChange"
            @current-change="currentChange"
            @refresh-change="handleList"
          >
            <template slot-scope="scope" slot="user" style="width:100px">
              <img style="width:30px;height:30px;" :src="scope.row.avatar">
              <span>{{scope.row.nickname}}</span>
            </template>

            <template slot-scope="scope" slot="no">
              <a style="color:blue" @click="handleBidDetail(scope.row)">{{scope.row.no}}</a>
            </template>
            <template slot-scope="scope" slot="is_ship" style="width:100px">
              <span>{{scope.row.is_ship ? scope.row.full_address : '自取'}}</span>
            </template>

            <template slot-scope="scope" slot="my_price" style="width:100px">
              <span>{{scope.row.my_price ? scope.row.my_price : '未出价'}}</span>
            </template>
            <template slot-scope="scope" slot="menu" style="width:100px">
              <el-button type="primary" size="small" @click="handleBidDetail(scope.row)">查看</el-button>
              <el-button
                v-if="! scope.row.my_price"
                type="primary"
                @click="handleBid(scope.row)"
                size="small"
              >竞标</el-button>
            </template>
          </avue-crud>
        </el-tab-pane>
        <el-tab-pane label="已中标" name="order">
          <avue-crud
            :option="tableOption"
            :data="tableData"
            :table-loading="tableLoading"
            :page="page"
            ref="crud"
            @size-change="sizeChange"
            @current-change="currentChange"
          >
            <template slot-scope="scope" slot="no">
              <span
                style="color:blue; cursor:pointer;"
                @click="handleDetail(scope.row)"
              >{{scope.row.no}}</span>
            </template>
            <template slot-scope="scope" slot="menu" style="width:100px">
              <span style="margin-left:10px" v-if="scope.row.flag == 9">
                <el-button type="primary" @click="handleCancelConfirm(scope.row)" size="small">确认退订单</el-button>
              </span>
              <el-button type="primary" @click="handleDetail(scope.row)" size="small">查看</el-button>
              <span style="margin-left:10px" v-if="isShip(scope.row.flag)">
                <el-button type="primary" @click="handleShip(scope.row)" size="small">发货</el-button>
                <el-button type="danger" @click="handleCancel(scope.row)" size="small">取消订单</el-button>
              </span>
            </template>

            <template slot="menuLeft">
              <div class="el-form el-form--inline">
                <div class="el-form-item">
                  <el-select v-model="orderFilter.flag" placeholder="请选择" @change="handleList()">
                    <el-option
                      v-for="(item,index) in flagOptions"
                      :key="item"
                      :label="item"
                      :value="index"
                    ></el-option>
                  </el-select>
                </div>

                <div class="el-form-item">
                  <el-date-picker
                    v-model="orderFilter.datetime"
                    type="daterange"
                    @change="handleList()"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  >></el-date-picker>
                </div>

                <div class="el-form-item">
                  <el-input
                    v-model="orderFilter.search"
                    style="width:220px"
                    placeholder="订单号，配送地址，产品名称"
                  ></el-input>
                </div>
                <div class="el-form-item">
                  <el-button type="primary" @click="handleList()">搜索</el-button>
                </div>
              </div>
            </template>

            <template slot-scope="scope" slot="is_ship">{{scope.row.is_ship ? '快递':'自取'}}</template>

            <template slot-scope="scope" slot="contact_name">{{scope.row.user.nickname}}</template>
            <template slot-scope="scope" slot="contact_phone">{{scope.row.user.phone}}</template>
            <template slot-scope="scope" slot="address">{{scope.row.address.address}}</template>

            <template slot-scope="scope" slot="flag">
              <span>{{scope.row.flag | flagDict}}</span>
            </template>
          </avue-crud>
        </el-tab-pane>
        <el-tab-pane label="未中标" name="otherOrder">
          <avue-crud
            :option="otherOption"
            :data="otherBidData"
            :table-loading="tableLoading"
            :page="page"
            ref="crud"
            @size-change="sizeChange"
            @current-change="currentChange"
            @refresh-change="handleList"
          >
            <template slot-scope="scope" slot="user" style="width:100px"></template>
            <template slot-scope="scope" slot="menu" style="width:100px"></template>
            <template slot-scope="scope" slot="no">
              <a style="color:blue" @click="handleBidDetail(scope.row)">{{scope.row.no}}</a>
            </template>
          </avue-crud>
        </el-tab-pane>
      </el-tabs>

      <bid-detail ref="bidDetail" method="GetBidOrdersShow"></bid-detail>

      <!-- 竞标单框 -->
      <el-dialog width="60%" title="竞标详情" :visible.sync="showBid" @close="clearBidDia">
        <el-row style="margin-top:20px">
          <h3 class="title">基本信息</h3>
          <div>买家备注: {{selectBid.remark}}</div>
        </el-row>
        <el-table :data="selectBid.product" stripe style="width: 100%">
          <el-table-column label="商品描述" width="200">
            <template slot-scope="scope">
              <div style="flex-direction: row;align-items: center;">
                <img
                  :src="scope.row.snapshot.cover"
                  style="width:40px;height:40px;vertical-align: middle;"
                >
                <span style="margin-left: 10px">{{ scope.row.snapshot.title }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="规格" width="auto">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.snapshot.sku }}</span>
            </template>
          </el-table-column>
          <el-table-column label="参考单价">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.snapshot.price}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="数量">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.count}}</span>
            </template>
          </el-table-column>
          <el-table-column label="小计">
            <template slot-scope="scope">
              <span
                style="margin-left: 10px"
              >{{ (scope.row.snapshot.price*scope.row.count) | numFilter}}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-row style="margin-top:20px">
          <span
            style="font-size:14px;float:right"
          >共 {{productCount}} 件商品 合计：￥{{totalAmount}}（不含运费：￥{{merchantInfo.freight}}）</span>
        </el-row>

        <el-row :span="16" style="margin-top:20px" v-if="bidAction">
          <el-form ref="form" :model="bidForm" label-width="120px">
            <el-form-item label="我的竞标价格">
              <el-input
                v-model="bidForm.price"
                type="number"
                min="0.00"
                step="0.01"
                placeholder="输入价格"
                :rules="[
      { required: true, message: '价格不能为空'},
    ]"
              ></el-input>
            </el-form-item>

            <el-form-item label="备注">
              <el-input type="textarea" rows="4" v-model="bidForm.remark"></el-input>
            </el-form-item>
          </el-form>
          <el-button style="float:right" type="primary" @click="bidThisOrder(bidForm)">出价</el-button>
        </el-row>
      </el-dialog>

      <!-- 详情弹出框 -->
      <el-dialog width="60%" title="订单详情" :visible.sync="showDetail">
        <div>
          <h3 class="title">基本信息</h3>
          <div>订单号: {{selectData.no}}</div>
          <div>下单时间: {{selectData.created_at}}</div>
          <div>订单状态: {{selectData.flag_str}}</div>
        </div>
        <div>
          <h3 class="title">收货信息</h3>

          <el-row :span="20" v-if="selectData.address">
            <el-col :span="8">
              <span>联系人: {{selectData.address.contact_name}}</span>
            </el-col>
            <el-col :span="8">
              <span>联系电话: {{selectData.address.contact_phone}}</span>
            </el-col>
            <el-col :span="8">
              <span>详细地址: {{selectData.address.address}}</span>
            </el-col>
          </el-row>
          <el-row :span="20" v-else>
            <el-col :span="8">
              <span>联系人:</span>
            </el-col>
            <el-col :span="8">
              <span>联系电话:</span>
            </el-col>
            <el-col :span="8">
              <span>详细地址:</span>
            </el-col>
          </el-row>
          <div>买家留言: {{selectData.remark}}</div>
        </div>

        <div>
          <h3 class="title">买家信息</h3>
          <el-row :span="20" v-if="selectData.address">
            <el-col :span="8">
              <span>用户: {{selectData.user.nickname}}</span>
            </el-col>
            <el-col :span="8">
              <span>电话: {{selectData.user.phone}}</span>
            </el-col>
          </el-row>
        </div>

        <div v-if="(selectData.flag >= 7)">
          <h3 class="title">发货信息</h3>
          <div v-html="showShipData"></div>
        </div>

        <div>
          <h3 class="title">商品信息</h3>

          <el-table :data="selectData.items" stripe style="width: 100%">
            <el-table-column label="商品描述" width="680">
              <template slot-scope="scope">
                <div style="flex-direction: row;align-items: center;">
                  <img
                    :src="scope.row.snapshot.cover"
                    style="width:40px;height:40px;vertical-align: middle;"
                  >
                  <span style="margin-left: 10px">{{ scope.row.snapshot.title }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="规格" width="auto">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.snapshot.sku }}</span>
              </template>
            </el-table-column>
            <el-table-column label="参考单价">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.snapshot.price}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="数量"></el-table-column>
            <el-table-column label="小计">
              <template slot-scope="scope">
                <span
                  style="margin-left: 10px"
                >{{ (scope.row.snapshot.price*scope.row.amount) | numFilter}}</span>
              </template>
            </el-table-column>
          </el-table>

          <el-row style="margin-top:20px">
            <!-- <span style="font-size:14px;float:right">共 1 件商品 合计：￥{{selectData.total_amount}}（含运费：￥{{selectData.freight}}）</span> -->
          </el-row>
        </div>
      </el-dialog>

      <!-- 填写发货相关信息 -->
      <el-dialog title="填写发货单" :visible.sync="showShip">
        <div>
          <h3 class="title">确定用户信息</h3>
          <el-row :span="20" v-if="selectData.address">
            <el-col :span="8">
              <span>联系人: {{selectAddress.contact_name}}</span>
            </el-col>
            <el-col :span="8">
              <span>联系电话: {{selectAddress.contact_phone}}</span>
            </el-col>
            <el-col :span="8">
              <span>详细地址: {{selectAddress.address}}</span>
            </el-col>
          </el-row>
        </div>

        <div>
          <h3 class="title">填写物流信息</h3>
          <el-input type="textarea" :rows="6" placeholder="请输入物流信息" v-model="shipData"></el-input>
          <div style="text-align:right">
            <el-button style="margin-top:30px;" type="primary" @click="handleShipClick()">发货</el-button>
          </div>
        </div>
      </el-dialog>

      <detail ref="detail" type="2"></detail>
      <detail-ship ref="detailShip" @refresh="handleList" type="2"></detail-ship>
    </basic-container>
  </div>
</template>

<script>
/* eslint-disable */
import { mapGetters } from "vuex";
import crudMixin from '@/mixins/crud'
import options from "./options.js";
import { isNull, arr2pojo, obj2pojo, validateResponse } from "@/util/util";
import { successMsg, errorMsg } from "@/util/message"
import { field, reField } from "./field";
import detail from "@/views/merchant/common/detail"
import detailShip from "@/views/merchant/common/detail_ship"


import bidDetail from "@/views/merchant/common/bid_detail";

export default {
  name: "role",
  mixins: [crudMixin],
  components: {
    bidDetail, detail, detailShip
  },
  data() {
    return Object.assign({}, options, {
      showShip: false,
      shipData: '',
      showDetail: false,
      showBid: false,
      bidAction: true,
      orderFilter: {  //订单筛选
        flag: 0,
        datetime: [],
        search: ''
      },
      selectData: '',  // 当前选择的订单
      selectBid: '',  //当前选择的竞标单
      selectAddress: {  //选择地址
        name: '',
        phone: '',
        address: '',
      },
      flagOptions: [
        '全部', '待付款', '待发货', '已发货', '已完成', '已关闭', '取消申请中'
      ],
      activeName: 'bidOrder',
      bidData: [],  // 竞标单关联显示
      merchantInfo: {},   //全局的商家资料数据
      bidForm: {  //竞标单form表
        id: '',
        price: '',
        remark: ''
      },
      otherBidData: []
    })
  },
  created() {
    //初始化数据格式
    this.handleList();
    this.merchantInfo = this.$store.state.merchant.info
  },
  watch: {
    "$route": "handleList"
  },
  mounted() { },
  computed: {
    productCount() {
      if (isNull(this.selectBid.product)) return 0
      return this.selectBid.product.length
    },
    totalAmount() {
      if (isNull(this.selectBid.product)) return 0
      let total = 0
      this.selectBid.product.forEach(element => {
        total += element.snapshot.price * element.count
      });
      return total
    },
    showShipData() {
      let reg = new RegExp("\n", "g");
      let str = this.selectData.ship_data.replace(reg, "<br>");
      return str
    }
  },
  filters: {
    flagDict: function (value) {
      var filter = options.tableOption.dicData.flag
      var str = ''
      filter.forEach(element => {
        if (value == element.value)        {
          str = element.label
        }
      });
      return str
    },
    numFilter: function (value) {
      let realVal = Number(value).toFixed(2)
      return realVal
    }
  },
  props: [],
  methods: {
    handleList(form = {}) {
      if (this.activeName == 'bidOrder')      {
        this.handleBidList()
      }
      if (this.activeName == 'order')      {
        this.handleOrderList()
      }
      if (this.activeName == 'otherOrder')      {
        this.handleOtherList()
      }
    },
    handleBidList()  //获取竞标单列表
    {
      this.tableLoading = true;
      let param = Object.assign({
        perPage: this.page.pageSize,
        page: this.page.currentPage
      });
      var vm = this
      this.$store
        .dispatch("GetBidOrders", param)
        .then(
          res => {
            this.tableLoading = false;
            if (res.data.status == 1)            {
              let _data = res.data.result.data || []
              //let _meta = res.data.result.meta || []

              this.bidData = _data;
              this.page.total = res.data.result.total;
            }
          }, error => {
            this.tableLoading = false;
          })
    },
    handleOtherList() {
      this.tableLoading = true;
      let param = Object.assign({
        perPage: this.page.pageSize,
        page: this.page.currentPage
      });
      var vm = this
      this.$store
        .dispatch("GetOtherOrder", param)
        .then(
          res => {
            this.tableLoading = false;
            if (res.data.status == 1)            {
              let _data = res.data.result.data || []
              //let _meta = res.data.result.meta || []

              this.otherBidData = _data;
              this.page.total = res.data.result.total;
            }
          }, error => {
            this.tableLoading = false;
          })
    },
    handleOrderList()  //获取我的订单列表
    {
      this.tableLoading = true;
      let param = Object.assign({
        perPage: this.page.pageSize,
        page: this.page.currentPage
      }, this.orderFilter);
      var vm = this

      this.$store
        .dispatch("GetMyBidOrders", param)
        .then(
          res => {
            this.tableLoading = false;
            if (res.data.status == 1)            {
              let _data = res.data.result.data || []
              let _meta = res.data.result.meta || []

              this.tableData = _data;
              this.page.total = _meta.total;
            }
          }, error => {
            this.tableLoading = false;
          })


    },
    tabClick(tab, event) {  //tab页切换
      this.handleList()
    },
    handleBid(row, type = 0) {   //进行竞标操作
      let vm = this
      vm.showBid = true
      if (type == 1)
      {
        vm.bidAction = false
      }
      else      {
        vm.bidAction = true
      }

      let param = {
        id: row.id
      }

      this.$store
        .dispatch("GetBidOrdersShow", param)
        .then(
          res => {
            if (res.data.status == 1)            {
              this.selectBid = res.data.result.data
            }
            else            {
              errorMsg(this, '获取详情错误')
            }
          }, error => {
            errorMsg(this, '获取详情错误')
          })

    },
    handleDetail(row) {
      this.$nextTick(() => {
        this.$refs.detail.handleShow(row.id)
      })
      // var vm = this
      // vm.showDetail = true
      // this.selectData = row
    },
    handleShip(row) {
      this.$nextTick(() => {
        this.$refs.detailShip.handleShow(row.id)
      })
      // var vm = this
      // vm.selectData = data
      // vm.selectAddress = data.address

      // if (!vm.selectData.is_ship)      {
      //   vm.shipAlert()
      // }
      // else      {
      //   vm.shipData = ''
      //   vm.showShip = true
      // }
    },
    handleShipClick() {
      //和上面这个差不多
      this.shipAlert()
    },
    search() {
      console.log(this.orderFilter)
    },
    shipAlert() {
      let vm = this
      let param = {
        id: this.selectData.id,
        ship_data: this.shipData
      }

      this.$confirm('是否确定订单即将发货？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$store
          .dispatch("ShipBidOrder", param)
          .then(
            res => {
              if (res.data.status == 1)              {
                vm.$message({
                  type: 'success',
                  message: '发货成功!'
                });

                vm.showShip = false
                //直接对flag进行更改
                let index = vm.selectData.$index

                if (vm.orderFilter.flag == 0)   //在全部这个分类
                {
                  vm.tableData[index].flag = 7;  //修改成为已发货状态
                }
                else                {
                  vm.tableData.splice(index)
                }
              }
              else              {
                errorMsg(vm, res.data.message)
              }
            }, error => {
            })
      }).catch(() => {
      });
    },
    isShip: function (value) {
      if (value == 2) return true
      if (value == 3) return true
      return false
    },
    //取消订单按钮
    handleCancel(row) {
      let vm = this
      let param = {
        id: row.id,
      }
      vm.selectData = row
      this.$confirm('是否取消订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$store
          .dispatch("CancelBidOrder", param)
          .then(
            res => {
              if (res.data.status == 1)              {
                vm.$message({
                  type: 'success',
                  message: '取消订单成功!'
                });
                //直接对flag进行更改
                let index = vm.selectData.$index
                //判断删除或者直接更改状态
                if (vm.orderFilter.flag == 0)   //在全部这个分类
                {
                  vm.tableData[index].flag = 5;  //修改成为取消订单确认
                }
                else                {
                  vm.tableData.splice(index)
                }
              }
              else              {
                errorMsg(vm, res.data.message)
              }
            }, error => {
            })
      }).catch(() => {
      });
    },
    bidThisOrder(formName) {  //竞标出价
      let vm = this
      this.bidForm.id = vm.selectBid.id
      if (isNull(vm.bidForm.price)) return errorMsg(this, '价格需要大于0');

      this.$confirm('是否确定出价？订单只能出价一次', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$store
          .dispatch("SetBidPrice", vm.bidForm)
          .then(
            res => {
              if (res.data.status == 1)              {
                vm.$message({
                  type: 'success',
                  message: '出价成功!'
                });
                vm.showBid = false
                vm.handleList()
              }
              else              {
                errorMsg(vm, res.data.message)
              }
            }, error => {
            })
      }).catch(() => {
      });
    },
    // 清理竞标单数据
    clearBidDia() {
      this.bidForm.price = ''
      this.bidForm.remark = ''
    },
    // 获取bid详情
    handleBidDetail(row) {
      this.$nextTick(() => {
        this.$refs.bidDetail.handleShow(row.id)
      })
    },
    handleCancelConfirm(row) {
      this.$confirm('是否确认用户可取消订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store
          .dispatch("bidorderCancelConfirm", { id: row.id })
          .then(res => {
            if (res.data.status == 1)            {
              this.$message({
                type: 'success',
                message: '订单已被取消!'
              });
              this.handleList()
            }
            else            {
              errorMsg(vm, res.data.message)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table-container {
  padding: 8px 10px;
}
.cancel {
  color: #000;
}

.card:last-child {
  border-bottom: 0px;
}

.card {
  margin-top: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #ededed;
}

.card .title {
  font-weight: 600;
  font-style: normal;
  color: rgba(0, 0, 0, 0.847058823529412);
}

.flex {
  flex: 1;
  flex-direction: row;
}
</style>
